package com.woniu.zhoukao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.zhoukao.entity.User;
import com.woniu.zhoukao.mapper.UserMapper;
import com.woniu.zhoukao.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuao
 * @since 2023-02-07 09:47:31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public void reg(String username, String password, String repass) {

        //要确保用户名的唯一性
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        User user = userMapper.selectOne(queryWrapper);
        if (user != null){
            throw new RuntimeException("用户名已被占用");
        }

        //password非空,repass非空且与password一致
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(repass) || !password.equals(repass)){
            throw new RuntimeException("两次输入密码不一致");
        }

        //校验通过,可以注册用户.
        User  regUser = new User();
        regUser.setUsername(username);
        regUser.setPassword(password);

        userMapper.insert(regUser);

    }

    @Override
    public void loginCheck(String userName, String password) {

        //根据用户名查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);

        User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            throw new RuntimeException("用户名错误");
        }

        if(!user.getPassword().equals(password)){
            throw new RuntimeException("密码错误");
        }

    }

    @Override
    public User getUserByUserName(String account) {
        //根据用户名查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",account);

        User user = userMapper.selectOne(queryWrapper);

        return user;
    }


}
